package com.magnificent.atlantis.client.ui.planner.panels.task.treetable.data;

import com.magnificent.atlantis.client.AtlantisConstants;
import org.jdesktop.swingx.treetable.AbstractTreeTableModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * User: Babanin
 * Date: 24.12.2008
 * Time: 1:51:07
 * <p/>
 * Feci quod potui, faciant meliora potentes.
 */
public class PlannerTableModel extends AbstractTreeTableModel {

    private PlannerTableNode root;

    public PlannerTableModel(PlannerTableNode root) {
        this.root = root;
    }

    public PlannerTableNode getRoot() {
        return root;
    }

    public int getColumnCount() {
        return AtlantisConstants.PLANNER_TASK_COLUMN_NAMES.length;
    }

    public Object getValueAt(Object oNode, int column) {
        if (column < 0) {
            return new PlannerTableShell("", (PlannerTableNode) oNode);
        }

        PlannerTableNode tableNode = (PlannerTableNode) oNode;
        return new PlannerTableShell("-", tableNode);
    }

    public Object getChild(Object parent, int index) {
        return ((PlannerTableNode) parent).getChildren().get(index);
    }

    public int getChildCount(Object parent) {
        return ((PlannerTableNode) parent).getChildCount();
    }

    public int getIndexOfChild(Object parent, Object child) {
        return ((PlannerTableNode) parent).getChildren().indexOf(child);
    }

    public boolean isCellEditable(Object node, int column) {
        return false;
    }

    public String getColumnName(int column) {
        return AtlantisConstants.PLANNER_TASK_COLUMN_NAMES[column];
    }

    public int getHierarchicalColumn() {
        return AtlantisConstants.TREE_COLUMN;
    }

    public void addNode(PlannerTableNode parentNode, PlannerTableNode newTableNode) {
        parentNode.getChildren().add(newTableNode);
        newTableNode.setParent(parentNode);

//        modelSupport.fireChildAdded(new TreePath(getParentPath(newTableNode)), getIndexOfChild(parentNode, newTableNode) - 1, newTableNode);
    }

    public void removeNode(PlannerTableNode node) {
        PlannerTableNode parentNode = node.getParent();

//        modelSupport.fireChildRemoved(new TreePath(getParentPath(node)), getIndexOfChild(parentNode, node), node);
        parentNode.getChildren().remove(node);
    }

    private Object[] getParentPath(PlannerTableNode node) {
        List<Object> treePath = new ArrayList<Object>();
        while (node.getParent() != null) {
            treePath.add(node.getParent());
            node = node.getParent();
        }

        Collections.reverse(treePath);

        return treePath.toArray();
    }
}
